import tools from 'libs/common/tools'

// 当前time是否为交易时间
const pIsTradeTime = time => {
  const now = tools.DateFormat(time, 'HH:mm');
  return (now >= '09:30' && now <= '11:35') || (now >= '13:00' && now <= '15:05')
}

// 循环调用方法
class Loop {
  static getInstance() { // 单例
    if (!Loop._instance) {
      Loop._instance = new Loop();
    }
    return Loop._instance;
  }

  timer = null;

  handlers = [];

  ticking = true;

  pause () {
    this.ticking = false;
  }

  continue () {
    this.ticking = true;
    // this.handlers.forEach(item => { this.register(item) });
    this.handlers.forEach(item => item());
    this.clock();
  }

  goOnTick () {
    this.ticking = true;
  }

  // 注册需要循环执行的方法
  register (...handlers) {
    handlers.forEach(item => {
      if (!this.handlers.includes(item)) {
        this.handlers.push(item);
      }
      if (this.ticking) {
        this.clock();
        item();
      }
    });
  }

  // 轮回
  clock () {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }

    this.timer = setInterval(() => {
      if (!pIsTradeTime(new Date()) || !this.ticking) {
        return;
      }
      this.handlers.forEach(item => item());
    }, 60000)
  }

  // 注销循环执行的方法
  unregister (...handlers) {
    handlers.forEach(item => {
      this.handlers.includes(item) && this.handlers.splice(this.handlers.indexOf(item), 1)
    })
  }

  clear () {
    clearInterval(this.timer);
    this.timer = null;
    this.handlers = [];
  }
}

export {
  Loop
}
